package cn.xxm.scene.config.aop;

import cn.xxm.scene.annotation.RoleAdvice;
import cn.xxm.scene.common.base.ExceptionCodeEum;
import cn.xxm.scene.entity.User;
import cn.xxm.scene.exception.ExceptionCast;
import cn.xxm.scene.utils.RedisKeyUtils;
import cn.xxm.scene.utils.RedisUtil;
import cn.xxm.scene.utils.WebHelper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by xxm
 * 2017-07-30 17:31
 */
@Aspect
@Component
@Slf4j
@Order(2)
public class LoginAuthorizeAspect {

    @Autowired
    private RedisUtil redis;

    @Before("@annotation(roleAdvice)")
    public void addBeforeLogger(JoinPoint joinPoint, RoleAdvice roleAdvice) {
        log.info("==========登录权限切面日志开始==========");

        boolean isMustLogin = roleAdvice.isMustLogin();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null != attributes && isMustLogin) {
        	 HttpServletRequest request = attributes.getRequest();
        	 // String flag = userLoginService.isLogin(request);
            String token = request.getParameter("token");
            String userTokenKey = RedisKeyUtils.getUserTokenKey(token);
            String userValue = redis.getString(userTokenKey);
            log.info(">>>the current request user:{}",userValue);
            if(StringUtils.isEmpty(userValue)){
                ExceptionCast.cast(ExceptionCodeEum.USER_SESSION_LOST);
            }
            // 重新刷新登录态
            redis.setString(userTokenKey,userValue,RedisKeyUtils.LOGIN_SESSION_EXPIRE);

            User user = JSONObject.parseObject(userValue, User.class);
            WebHelper.setRequestAttribute(token,user);
        }
    }
    
}
